﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using System.Device.Location;

namespace Positions
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            StartAgent();
            UpdatePosition();
        }
        private const string TASK_NAME = "Positions";

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            StartAgent();
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            StopAgentIfStarted();
        }

        private void StartAgent()
        {
            StopAgentIfStarted();

            PeriodicTask task = new PeriodicTask(TASK_NAME);
            task.Description = "GPS Positions Recorder";
            ScheduledActionService.Add(task);

            // If we're debugging, attempt to start the task immediately
            ScheduledActionService.LaunchForTest(TASK_NAME, new TimeSpan(0, 0, 1));

        }

        private void StopAgentIfStarted()
        {
            if (ScheduledActionService.Find(TASK_NAME) != null)
            {
                ScheduledActionService.Remove(TASK_NAME);
            }
        }

        private void UpdatePosition()
        {
            GeoCoordinateWatcher GeoCoordinateWatcher = new GeoCoordinateWatcher();
            bool ok = GeoCoordinateWatcher.TryStart(false, new TimeSpan(0, 0, 10));
            var g= GeoCoordinateWatcher.Position.Location;
            if (!g.IsUnknown)
            {
                Latitude.Text=""+g.Latitude;
                Longitude.Text = ""+g.Longitude;
                Altitude.Text = "" + g.Altitude;
                Course.Text = "" + g.Course;
                Speed.Text = "" + g.Speed;
                HorizontalAccuracy.Text = "" + g.HorizontalAccuracy;
                
                VerticalAccuracy.Text = "" + g.VerticalAccuracy;
            }
            else
            {
                Error.Text = "Errore GPS";
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            UpdatePosition();
            StartAgent();
        }
    }
}